<template>
    <div class="page-root">
        <h2 class="main-title">入住记录列表</h2>
        <!-- 查询条件 -->
        <el-form :inline="true" :model="searchForm" class="search-bar">
            <el-form-item label="客户名：">
                <el-input v-model="searchForm.name" placeholder="请输入名称" clearable />
            </el-form-item>
            <el-form-item label="入住时间区间：">
                <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="~" start-placeholder="开始日期"
                    end-placeholder="结束日期" value-format="YYYY-MM-DD" clearable />
            </el-form-item>
            <el-form-item label="状态：">
                <el-select v-model="searchForm.status" clearable placeholder="请选择状态" style="width: 120px">
                    <el-option label="全部" value="" />
                    <el-option label="自理老人" value="自理老人" />
                    <el-option label="护理老人" value="护理老人" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="init">查询</el-button>
                <el-button type="success" @click="handleAdd">添加</el-button>
                <el-button @click="handleReset">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 表格数据 -->
        <el-table :data="tableData" border style="width: 100%; margin-top:2%; background:#f5f7fa;"
            :header-cell-style="{ background: '#f9fafc', color: '#333', textAlign: 'center', fontWeight: 'bold' }"
            :cell-style="{ textAlign: 'center' }" v-loading="loading" class="main-table">
            <el-table-column prop="client.name" label="客户姓名" min-width="10%">
                <template #default="scope">{{ scope.row.client.name }}</template>
            </el-table-column>
            <el-table-column prop="checkinRecord.checkinDate" label="入住时间" min-width="13%">
                <template #default="scope">{{ formatDate(scope.row.checkinRecord.checkinDate) }}</template>
            </el-table-column>
            <el-table-column prop="checkinRecord.checkoutDate" label="退住时间" min-width="13%">
                <template #default="scope">
                    {{ scope.row.checkinRecord.checkoutDate ? formatDate(scope.row.checkinRecord.checkoutDate) : '-' }}
                </template>
            </el-table-column>
            <el-table-column prop="checkinRecord.bedNo" label="床位号" min-width="12%">
                <template #default="scope">
                    {{ getBedNo(scope.row) }}
                </template>
            </el-table-column>
            <el-table-column prop="checkinRecord.status" label="状态" min-width="10%">
                <template #default="scope">
                    <el-tag v-if="scope.row.client.userId == undefined" type="info" size="small"
                        style="background:#e4b62a;color:#fff;border:none">自理老人</el-tag>
                    <el-tag v-else type="success" size="small"
                        style="background:#73c600;color:#fff;border:none">护理老人</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="checkinRecord.userId" label="办理人" min-width="10%">
                <template #default="scope">
                    <span class="user-link" @click="showUserDialog(scope.row.checkinRecord.userId)">
                        {{ getUserName(scope.row.checkinRecord.userId) }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="操作" min-width="13%">
                <template #default="scope">
                    <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                    <el-button
                        v-if="compareTime(scope.row.checkinRecord.checkoutDate)" type="primary" size="small"
                        @click="handleUpdate(scope.row)">
                        修改合约时间
                    </el-button>

                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-bar">
            <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.size"
                :total="pagination.total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange" @current-change="handlePageChange" />
        </div>

        <AddCheckinDialog ref="addNew" @success="init" />
        <UserInfoDialog ref="userDialogRef" />
        <EditEndTimeDialog ref="editDialogRef" @refresh="init" />
    </div>
</template>
  
<script setup>
import { ref, reactive, onMounted, inject } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import qs from 'qs'
import AddCheckinDialog from '@/components/checkin/AddCheckinDialog.vue';
import UserInfoDialog from '@/components/UserInfoDialog.vue'
import EditEndTimeDialog from '@/components/checkin/EditEndTimeDialog.vue'

const axios = inject('axios')
const userDialogRef = ref(null)
const editDialogRef = ref(null)
const loading = ref(false)
const tableData = ref([])
const addNew = ref(false)
const pagination = reactive({ page: 1, size: 10, total: 0 })
const searchForm = reactive({ name: '', dateRange: [], status: '' })

const handleReset = () => {
    searchForm.name = ''
    searchForm.dateRange = []
    searchForm.status = ''
    init()
}

const userDict = ref({})
const getUserDict = async () => {
    try {
        const { data } = await axios.get('/user/listAll')
        userDict.value = {}
        data.data.forEach(u => { userDict.value[u.userId] = u })
    } catch (e) { userDict.value = {} }
}
const getUserName = userId => userDict.value?.[userId]?.username || '未知'

const showUserDialog = (userId) => {
    const userInfo = userDict.value[userId]
    if (userDialogRef.value && userInfo) userDialogRef.value.open(userInfo)
    else ElMessage.warning('无法找到用户信息')
}

const getQueryParams = () => ({
    name: searchForm.name,
    checkinDateStart: searchForm.dateRange[0] || '',
    checkinDateEnd: searchForm.dateRange[1] || '',
    status: searchForm.status,
    page: pagination.page,
    size: pagination.size,
})
const init = async () => {
    loading.value = true
    try {
        const { data } = await axios.get('/checkinRecord/checkinPage', {
            params: getQueryParams(),
        })
        if (data.status === 200) {
            tableData.value = data.data || []
            pagination.total = data.total || 0
        } else {
            tableData.value = []
            pagination.total = 0
            ElMessage.warning(data.msg || '查询失败')
        }
    } catch (e) {
        tableData.value = []
        pagination.total = 0
        ElMessage.error('查询失败')
    } finally {
        loading.value = false
    }
}
const handlePageChange = (val) => { pagination.page = val; init() }
const handleSizeChange = (val) => { pagination.size = val; pagination.page = 1; init() }
const handleDelete = (row) => {
    ElMessageBox.confirm('确认删除该入住记录？', '提示', { type: 'warning' })
        .then(async () => {
            try {
                const { data } = await axios.post('/checkinRecord/delete',
                    qs.stringify({ recordId: row.checkinRecord.recordId }),
                )
                if (data.status === 200) {
                    ElMessage.success('删除成功')
                    init()
                } else {
                    ElMessage.warning(data.msg || '删除失败')
                }
            } catch (e) {
                ElMessage.error('删除失败')
            }
        })
        .catch(() => { })
}
const handleAdd = () => { addNew.value.open() }

const handleUpdate = (row) => {
    editDialogRef.value.open(row)
}

let bedDict = ref({})
const initBedDict = async () => {
    try {
        const { data } = await axios.get('/bed/listAll')
        bedDict.value = {}
        data.data.forEach(bed => { bedDict.value[bed.bedId] = bed.building + "-" + bed.floorNumber + "-" + bed.roomNumber + "-" + bed.bedNumber })
    } catch (e) {
        bedDict.value = {}
    }
}
const getBedNo = (row) => {
    if (!row || !row.checkinRecord || !row.checkinRecord.bedId) return '-'
    return bedDict.value[row.client.bedId] || '未知床位'
}
const formatDate = (str) => {
    if (!str) return '-'
    return str.split(' ')[0]
}

const compareTime = (time) => {
  if (!time) return false
  // 兼容各类字符串和Date类型
  let t = typeof time === 'string' ? time.replace(/-/g, '/') : time
  const endDate = new Date(t)
  if (isNaN(endDate)) return false
  return endDate.getTime() > Date.now()
}


onMounted(() => {
    getUserDict()
    initBedDict()
    init()
})
</script>
  
<style scoped>
.page-root {
    width: 100%;
    min-height: 100%;
    box-sizing: border-box;
    padding: 0 3%;
}

.main-title {
    font-size: 27.2px;
    font-weight: bold;
    color: #333;
    margin-top: 0;
    margin-bottom: 2%;
}

.search-bar {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    gap: 1.2em;
    margin-bottom: 1.5%;
    align-items: center;
}

.el-table {
    background: #f5f7fa;
}

.pagination-bar {
    width: 100%;
    display: flex;
    justify-content: flex-end;
    margin-top: 2%;
    margin-bottom: 2%;
}

.user-link {
    color: #409EFF;
    cursor: pointer;
    text-decoration: underline;
}

.user-link:hover {
    color: #1872dd;
}
</style>
  